import request from "@/services/interceptors";
import type { ActionType, ProColumns } from "@ant-design/pro-components";
import { ProTable } from "@ant-design/pro-components";
import { useEffect, useRef, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { ExamType } from "@/types";
import { Button, Modal } from "antd";
import { useRequest } from "ahooks";
import ExamChart from "./ExamChart";
import { VerticalAlignBottomOutlined } from "@ant-design/icons";

const ExamRecord = () => {
  const actionRef = useRef<ActionType>(null);
  const { examId } = useParams();
  const [visible, setVisible] = useState(false);
  const navigate = useNavigate();

  const { data: examResult, runAsync: examResultStatList } = useRequest(
    request.sgks.examResultStatList,
    {
      manual: true,
    }
  );

  const columns: ProColumns<ExamType>[] = [
    {
      title: "学员ID",
      dataIndex: "studentId",
    },
    {
      title: "学员名称",
      dataIndex: "studentName",
    },
    {
      title: "学号",
      dataIndex: "studentNo",
    },

    {
      title: "交卷时间",
      dataIndex: "submitTime",
    },
    {
      title: "总分",
      dataIndex: "totalScore",
    },
    {
      title: "操作",
      render: (_, record) => {
        return [
          <Button
            type="link"
            onClick={() => {
              navigate({
                pathname: "/exam/result",
                search: `?examId=${examId}&studentId=${record.studentId}`,
              });
            }}
          >
            查看
          </Button>,
        ];
      },
    },
  ];

  useEffect(() => {
    if (examId) {
      examResultStatList({ examId: +examId });
    }
  }, [examId, examResultStatList]);

  const { runAsync: examResultExportList, loading: exportLoading } = useRequest(
    request.sgks.examResultExportList,
    { manual: true }
  );

  const exportEaxmResult = async () => {
    const res: any = await examResultExportList(
      {
        examId: +examId,
      },
      {
        format: "blob",
      }
    );
    const blob = new Blob([res.data]);
    const downloadUrl = window.URL.createObjectURL(blob);
    // 创建 a 标签并触发下载
    const a = document.createElement("a");
    a.href = downloadUrl;
    // 可根据实际情况设置文件名
    a.download = `考试记录${examId}_${Date.now()}.xlsx`;
    document.body.appendChild(a);
    a.click();
    a.remove();
    window.URL.revokeObjectURL(downloadUrl);
  };

  return (
    <>
      <ProTable<ExamType>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        request={async (params, sort, filter) => {
          console.log(params, sort, filter);
          const res = await request.sgks.examResultListList({
            examId: examId,
            pageNo: params.current,
            pageSize: params.pageSize,
          } as any);

          return {
            data: res.data.records,
            total: res.data?.totalCount,
          };
        }}
        columnsState={{
          persistenceKey: "ExamRecord_List",
          persistenceType: "localStorage",
          defaultValue: {
            option: { fixed: "right", disable: true },
          },
        }}
        rowKey="id"
        search={false}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
        toolBarRender={() => [
          <Button
            type="primary"
            icon={<VerticalAlignBottomOutlined />}
            onClick={exportEaxmResult}
            loading={exportLoading}
            disabled={exportLoading}
          >
            导出
          </Button>,
          <Button
            hidden={!examResult?.data}
            type="primary"
            onClick={() => {
              setVisible(true);
            }}
          >
            查看成绩分布
          </Button>,
        ]}
      />
      <Modal
        footer={null}
        open={visible}
        onCancel={() => setVisible(false)}
        width={800}
        height={1000}
        title="考试成绩分布"
      >
        <ExamChart {...examResult?.data} />
      </Modal>
    </>
  );
};

export default ExamRecord;
